package com.shop.web.servlet;

import java.io.IOException;

import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.misc.BASE64Encoder;
import com.shop.domain.OrderItem;

public class ExportServlet extends HttpServlet {

	private static final long serialVersionUID = 7715865743257658440L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		List<OrderItem> ranks = (List<OrderItem>) request.getServletContext().getAttribute("ranks");
		response.setHeader("Content-Type", getServletContext().getMimeType("rank.csv"));
		Date date = new Date(System.currentTimeMillis());// 构造java.sql.Date 当前时间
		String filename = "商城榜单数据" + System.currentTimeMillis() + ".csv";
		// 转化中文文件名称
		String agent = request.getHeader("user-agent");
		if (agent.contains("MSIE")) {
			filename = URLEncoder.encode(filename, "utf-8");
		} else if (agent.equals("Mozilla")) {
			// 火狐
			BASE64Encoder base64Encoder = new BASE64Encoder();
			filename = "=?UTF-8?B?" + new String(base64Encoder.encode(filename.getBytes("UTF-8"))) + "?=";
		}
		response.setHeader("Content-Disposition", "attachment;filename = " + filename);

		// 设置响应流编码 gbk
		response.setCharacterEncoding("gbk");

		// 开始下载文件
		PrintWriter out = response.getWriter();
		// 先写表头
		out.println("排名,商品编号,名称,单价,销售数量");
		for (int i = 0; i < ranks.size(); i++) {
			OrderItem item = ranks.get(i);
			out.println((i + 1) + "," + item.getProduct_id() + "," + convert(item.getProduct().getName()) + ","
					+ item.getProduct().getPrice() + "," + item.getBuynum());
		}

	}

	private String convert(String name) {
		name = name.replaceAll("\"", "\"\"");
		return "\"" + name + "\"";
	}
}
